package com.cloud.servicegreyrelease2.compoment.aspect;

import com.cloud.servicegreyrelease2.compoment.threadlocal.UserIdThreadLocal;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class GreyAspect {

    //切面，拦截所有请求
    @Pointcut(value = "execution(* com.cloud.servicegreyrelease2.controller.*.*(..))")
    public void pointcut(){}

    //在执行业务逻辑前
    @Before(value = "pointcut()")
    public void getUserId(JoinPoint joinPoint){
        //拿到 HttpServletRequest 对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //获取到 userId
        String userId = request.getHeader("userId");
        Map<String,String> map = new HashMap<>();
        map.put("userId",userId);
        //放到ThreadLocal 对象中，到 GreyRule中使用 ，切记：使用完后不要忘了释放
        UserIdThreadLocal.set(map);
    }
}
